#
# Licensed under the Apache License, Version 2.0 (the “License”);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an “AS IS” BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""
Django settings for crapi_site project.

Generated by 'django-admin startproject' using Django 2.2.13.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

from django.core.exceptions import ImproperlyConfigured

DEFAULT_LIMIT = 10
DEFAULT_OFFSET = 0
MAX_LIMIT = 100


def get_env_value(env_variable):
    try:
        return os.environ[env_variable]
    except KeyError:
        error_msg = f"Set the {env_variable} environment variable"
        raise ImproperlyConfigured(error_msg)


# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_env_value("SECRET_KEY")

# Enable it if Testing
IS_TESTING = os.environ.get("IS_TESTING", False)

# SECURITY WARNING: don't run with debug turned on in production!
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
DEBUG = os.environ.get("DEBUG", False)
if LOG_LEVEL == "DEBUG":
    DEBUG = True

ALLOWED_HOSTS = ["*"]

API_GATEWAY_URL = get_env_value("API_GATEWAY_URL")
API_GATEWAY_USERNAME = "vendorcrapi"
API_GATEWAY_PASSWORD = "Pa$$4Vendor_1"

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "corsheaders",
    "health_check",
    "health_check.db",
    "core",
    "crapi",
    # 'crapi.apps.CRAPIConfig',
    # 'user.apps.UserConfig',
    "django_extensions",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.BrokenLinkEmailsMiddleware",
    "django.middleware.common.CommonMiddleware",
]

CORS_ORIGIN_ALLOW_ALL = True

ROOT_URLCONF = "crapi_site.urls"

TEST_RUNNER = "xmlrunner.extra.djangotestrunner.XMLTestRunner"

TEST_OUTPUT_DIR = os.path.join(BASE_DIR, "test-reports")

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "crapi_site.wsgi.application"

REST_FRAMEWORK = {
    "DEFAULT_RENDERER_CLASSES": [
        "rest_framework.renderers.JSONRenderer",
    ],
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
    "PAGE_SIZE": MAX_LIMIT,
    "DEFAULT_FILTER_BACKENDS": ("django_filters.rest_framework.DjangoFilterBackend",),
    "UNAUTHENTICATED_USER": None,  # Needed once you disable django.contrib.auth
}
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "standard": {"format": "%(asctime)s %(name)-12s [%(levelname)s]: %(message)s"},
        "console": {"format": "%(name)-12s %(levelname)-8s %(message)s"},
    },
    "handlers": {
        "file": {
            "level": LOG_LEVEL,
            "class": "logging.FileHandler",
            "filename": BASE_DIR + "/debug.log",
            "formatter": "standard",
        },
        "console": {
            "level": LOG_LEVEL,
            "class": "logging.StreamHandler",
            "formatter": "console",
        },
    },
    "root": {
        "handlers": ["file", "console"],
        "level": LOG_LEVEL,
    },
    "django.request": {
        "handlers": ["file"],
        "level": LOG_LEVEL,
    },
    "djongo": {
        "level": LOG_LEVEL,
        "handlers": ["console"],
        "propogate": True,
    },
}

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": get_env_value("DB_NAME"),
        "USER": get_env_value("DB_USER"),
        "PASSWORD": get_env_value("DB_PASSWORD"),
        "HOST": get_env_value("DB_HOST"),
        "PORT": get_env_value("DB_PORT"),
        "TEST": {
            "NAME": "test_crapi",
            "USER": get_env_value("DB_USER"),
        },
        "CONN_MAX_AGE": 0,
    },
    "mongodb": {
        "ENGINE": "djongo",
        "NAME": get_env_value("MONGO_DB_NAME"),
        "CLIENT": {
            "host": get_env_value("MONGO_DB_HOST"),
            "port": int(get_env_value("MONGO_DB_PORT")),
            "username": get_env_value("MONGO_DB_USER"),
            "password": get_env_value("MONGO_DB_PASSWORD"),
            "authSource": "admin",
        },
        "TEST": {"NAME": "test_crapi_mongo", "USER": get_env_value("MONGO_DB_USER")},
    },
}

# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

# AUTH_PASSWORD_VALIDATORS = [
#     {
#         'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
#     },
#     {
#         'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
#     },
#     {
#         'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
#     },
#     {
#         'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
#     },
# ]

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

# USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = "/static/"

IDENTITY_VERIFY = "http://{}/identity/api/auth/verify".format(
    get_env_value("IDENTITY_SERVICE")
)
IDENTITY_LOGIN = "http://{}/identity/api/auth/login".format(
    get_env_value("IDENTITY_SERVICE")
)
IDENTITY_HEALTH = "http://{}/identity/health_check".format(
    get_env_value("IDENTITY_SERVICE")
)
TLS_ENABLED = os.environ.get("TLS_ENABLED")
if TLS_ENABLED and (TLS_ENABLED.lower() in ["true", "1", "yes"]):
    IDENTITY_VERIFY = "https://{}/identity/api/auth/verify".format(
        get_env_value("IDENTITY_SERVICE")
    )
    IDENTITY_LOGIN = "https://{}/identity/api/auth/login".format(
        get_env_value("IDENTITY_SERVICE")
    )
    IDENTITY_HEALTH = "https://{}/identity/health_check".format(
        get_env_value("IDENTITY_SERVICE")
    )
